package cn.lzm.server.tcp;

import cn.lzm.server.Server;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import io.vertx.core.parsetools.RecordParser;

/**
 * @author lzm
 * @Date 2024/11/5
 * @description 基于tcp协议的服务器 测试vertx来读取固定长度的消息
 */
public class VertxTcpServerV3 implements Server {

    @Override
    public void start(int port) {
        Vertx vertx = Vertx.vertx();
        NetServer server = vertx.createNetServer();
        server.connectHandler(socket -> {
            String msg = "hello, server! hello, server! hello, server! hello, server!";
            int messageLength = msg.getBytes().length;
            RecordParser parser = RecordParser.newFixed(messageLength);
            parser.setOutput(buffer -> {
                String str = new String(buffer.getBytes());
                System.out.println("从客户端收到的消息：" + str);
                if (msg.equals(str)) {
                    System.out.println("good");
                }
            });
            socket.handler(parser);
        });

        server.listen(port, result -> {
            if (result.succeeded()) {
                System.out.println("Tcp server started on port " + port);
            } else {
                System.out.println("Failed to start Tcp server: " + result.cause());
            }
        });
    }

    public static void main(String[] args) {
        VertxTcpServerV3 tcpServer = new VertxTcpServerV3();
        tcpServer.start(8404);
    }

}
